
// import * as d3 from "../lib/d3.js";
import * as d3 from "d3";
import {whenEnabled} from "./util.js";
import * as utc from "../util/utc.js";
import {tr} from "./translations.js";
import {$} from "../util/seq.js";

export function defineDateField(container, sessionStore, layerAgent) {

    const field = container.select("[data-name=date-field]");
    const button = container.select("#change-tz");
    const zones = button.selectAll("[data-tz]").nodes();

    function formatDate(validTime, dateFormat, displayTimezone, tzLabel) {
        const isLocal = displayTimezone === "device";
        return validTime && dateFormat && tzLabel ?
            utc.print(isLocal ? utc.toLocalParts(validTime) : validTime, dateFormat).replace("{TZ}", tzLabel) :
            tr`N/A`;
    }

    function updateDOM() {
        const layer = layerAgent.value();
        const validTime = layer?.validTime();
        const dateFormat = layer?.dateFormat();
        const displayTimezone = sessionStore.get("display_timezone") ?? "device";
        const matchedZone = zones.filter(e => e.dataset.tz === displayTimezone)[0];
        const tzLabel = matchedZone ? d3.select(matchedZone).text() : "";
        field.text(formatDate(validTime, dateFormat, displayTimezone, tzLabel));
    }

    button.on($`click`, whenEnabled(() => {
        const next = zones.map(e => e.hidden).indexOf(false);
        sessionStore.set("display_timezone", zones[next].dataset.tz);
    }));

    sessionStore.on($`change:display_timezone`, tz => {
        const active = zones.map(e => e.dataset.tz).indexOf(tz);
        const next = (active + 1) % zones.length;
        zones.forEach((e, i) => e.hidden = i !== next);
        updateDOM();
    });

    layerAgent.on($`update`, updateDOM);
}
